from service.utils import random_pause, get_usd_to_cny_rate
from service.csfloat import request_csfloat_list
from service.steamdt import request_steamdt_by_api
from rich.progress import Progress
from service.utils import logger
import math


# 整合数据
def integrate_data(params=[]):
    result = []
    progress = Progress()
    progress.start()

    if len(params) == 0:
        progress.stop()
        return result

    # 请求SteamDT数据
    task_steamdt = progress.add_task("获取steamdt数据...", total=1)
    res_steamdt = request_steamdt_by_api(params)
    for d in res_steamdt:
        to_add = {
            "饰品名": d["marketHashName"],
        }
        required_platform = ["YOUPIN"]  # 需要记录的平台
        for p in d["dataList"]:
            if p["platform"] in required_platform:
                to_add[f"{p['platform']}价格"] = p["sellPrice"]
        result.append(to_add)
    progress.update(task_steamdt, advance=1)

    # 获取汇率
    exchange_rate = get_usd_to_cny_rate()

    # 请求csfloat数据
    task_csfloat = progress.add_task("处理常规饰品...", total=len(params))

    def get_csfloat_data(param):
        res_csfloat = request_csfloat_list(param)
        if len(res_csfloat.get("data", [])) > 0:
            data_csfloat = res_csfloat["data"][0]
            for idx, item in enumerate(result):
                if data_csfloat["item"]["market_hash_name"] == item["饰品名"]:
                    csfloat_price = data_csfloat["price"] / 100 * exchange_rate
                    logger.info(f"{item['饰品名']} 查询成功")
                    cost = csfloat_price * 1.028 * 0.99  # 成本
                    no_vip_profit = item["YOUPIN价格"] * 0.98 - cost
                    no_vip_profit_rate = (no_vip_profit / cost) if cost > 0 else None
                    vip_profit = item["YOUPIN价格"] - cost
                    vip_profit_rate = (vip_profit / cost) if cost > 0 else None
                    result[idx]["csfloat价格"] = csfloat_price
                    item["非大会员利润"] = no_vip_profit
                    item["非大会员利润率"] = no_vip_profit_rate
                    item["大会员利润"] = vip_profit
                    item["大会员利润率"] = vip_profit_rate
                    break
        progress.update(task_csfloat, advance=1)
        random_pause()

    for param in params:
        get_csfloat_data(param)

    logger.info("常规饰品查询成功")
    progress.stop()

    return result
